var moment = require('moment');
var config = require('./config')();
var redis = require("./redis");

module.exports.web=function(app){
  app.get('/chat', function(req, res, next) {
    res.render('onchat', { title: config.chatTitle});
  });

  app.post('/onchat',function(req, res) {
	res.render('chat', {title: config.chatTitle, username: req.body.username });
  });
};

var namespace = "default";
var onlineUsers = [], historyContents = [];
//暂未使用
var hisContentCacheKey = "cache:content";

redis.on("err",function(err){
 console.log(err);
});
module.exports.connect = function(io){
	io.on('connection',function(socket){
		
		var req = socket.request;
		
		console.log('a user connected');

		socket.on('disconnect',function(){
			socket.get("nickname",function(err,username){
				//获取在线列表
				redis.hget(namespace,"onlineUsers",function(err,result){
					onlineUsers = JSON.parse(result);
					var index = onlineUsers.indexOf(username);
					if(index != -1){
						//删除退出用户
						onlineUsers.splice(index , 1);
						//重新设置在线用户列表
						redis.hset(namespace,"onlineUsers",JSON.stringify(onlineUsers),redis.print);
						//设置在线人数-1
						redis.hincrby(namespace,"onlineCount",-1,function(err,count){
							if(count != 0) io.emit('loginout', {onlineUsers : onlineUsers.join("|"), username : username, onlineCount : count, action : 'logout'}, null);
						});
					}
				});
			});
		});

		socket.on('message',function(user){
			var timeStr = moment().format('YYYY-MM-DD HH:mm:ss');
			user.time = timeStr;
			//查询聊天记录
			redis.sort("timeStamp","by",namespace+":*->historyContents","DESC",0,-1).then(function(result){
				if(result!=null){
					historyContents = JSON.parse(result);
				}
				io.emit('chat message', user);
				//缓存聊天记录
				historyContents.push(JSON.stringify(user));
				redis.hmset(namespace+":"+user.userid,{"historyContents":JSON.stringify(historyContents),"timeStamp":new Date().getTime()},redis.print);
			});
		});

		socket.on("open",function(user){
			socket.set("nickname",user.username,function(){
				console.log("socket存储nickname="+user.username);
			});
			
			 //设置在线人数列表
			redis.hget(namespace,"onlineUsers",function(err,result){
				if(result != ''){
					onlineUsers = JSON.parse(result);
				}
				onlineUsers.push(user.username);
				//设置在线人数+1
				redis.hincrby(namespace,"onlineCount",1,function(err,count){
					//推送历史聊天记录
					redis.sort("timeStamp","by",namespace+":*->historyContents","DESC",0,5).then(function(result){
						historyContents = JSON.parse(userContent);
						io.emit('loginout', {onlineUsers : onlineUsers.join("|"), username : user.username, onlineCount : count, action : 'login'}, historyContents);
					});
					/**redis.exists(hisContentCacheKey).then(function(exist){
						var userContent = "";
						if(exist){
							var userContent = redis.lrange(hisContentCacheKey,0,-1);
							historyContents = JSON.parse(userContent);
							io.emit('chat history', historyContents);
						}else{
							redis.sort(namespace,"by","historyContents->created_at","DESC",0,10,'store',hisContentCacheKey).then(function(size){
								//缓存生存时间为10分钟
								db.expire(cacheKey,600);
								var userContent = redis.lrange(hisContentCacheKey,0,-1);
								historyContents = JSON.parse(userContent);
							    io.emit('chat history', historyContents);
							});
						}
					});**/
				});
				//重新设置在线人数列表
				redis.hset(namespace,"onlineUsers",JSON.stringify(onlineUsers),redis.print);
			});
		});
	});
}